<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- AdThrive Head Tag Manual -->
    <script data-no-optimize="1" data-cfasync="false">
      (function (w, d) {
        w.adthrive = w.adthrive || {};
        w.adthrive.cmd = w.adthrive.cmd || [];
        w.adthrive.plugin = "adthrive-ads-manual";
        w.adthrive.host = "ads.adthrive.com";
        var s = d.createElement("script");
        s.async = true;
        s.referrerpolicy = "no-referrer-when-downgrade";
        s.src =
          "https://" +
          w.adthrive.host +
          "/sites/643436a4e6d20859e40a446b/ads.min.js?referrer=" +
          w.encodeURIComponent(w.location.href) +
          "&cb=" +
          (Math.floor(Math.random() * 100) + 1);
        var n = d.getElementsByTagName("script")[0];
        n.parentNode.insertBefore(s, n);
      })(window, document);
    </script>
    <!-- End of AdThrive Head Tag -->

    <!-- Global site tag (gtag.js) - Google Analytics -->

    <script
      async
      src="https://www.googletagmanager.com/gtag/js?id=UA-79254642-6"
    ></script>

    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag() {
        dataLayer.push(arguments);
      }
      gtag("js", new Date());

      gtag("config", "UA-79254642-6");
    </script>

    <meta charset="utf-8" />
    <title>Most basic hierarchical edge bundling with d3.js</title>
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta
      name="description"
      content="Using d3.js and javascript to create a very basic hierarchical edge bundling"
    />
    <meta
      name="keywords"
      content="Data, Dataviz, Datavisualization, Javascript, JS, d3.js, bubble plot"
    />
    <meta name="author" content="Yan Holtz" />
    <link rel="icon" href="../img/logo/D3_single_small.png" />

    <meta
      property="og:title"
      content="Most basic hierarchical edge bundling plot in d3.js"
    />
    <meta
      property="og:image"
      content="https://www.d3-graph-gallery.com/img/logo/D3_full_medium.png"
    />
    <meta
      property="og:description"
      content="Using d3.js to create a very basic hierarchical edge bundling"
    />

    <!-- Bootstrap core CSS -->
    <link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet" />

    <!-- Custom fonts for this template -->
    <link
      href="../vendor/font-awesome/css/font-awesome.min.css"
      rel="stylesheet"
      type="text/css"
    />

    <!-- Custom styles for this template -->
    <link href="../css/agency.css" rel="stylesheet" />

    <!-- PRISM -->
    <script src="../LIB/prism.js"></script>
    <link href="../LIB/prism.css" rel="stylesheet" />

    <!-- D3.JS v4 -->
    <script src="../js/d3.v4.js"></script>

    <!-- JQUERY -->
    <script src="../vendor/jquery/jquery.min.js"></script>

    <!-- HTML TO CANVAS -->
    <script src="../js/html2canvas.js"></script>

    <!-- Function to parse html and js code chunks made by Yan Holtz -->
    <script src="../js/myParser.js"></script>
  </head>

  <body id="page-top">
    <!-- THIS ALLOWS TO INSERT THE MENU THAT IS STORED IN A MENU.HTML FILE-->
    <nav class="navbar navbar-expand-lg fixed-top" id="mainNav"></nav>
    <script>
      $(function () {
        $("#mainNav").load("../html_chunk/menu.html");
      });
    </script>

    <!-- THIS ALLOWS TO INSERT THE MODAL OF THE MENU THAT IS STORED IN A MENU_MODAL.HTML FILE-->
    <div id="modal_menu_insertion"></div>
    <script>
      $(function () {
        $("#modal_menu_insertion").load("../html_chunk/menu_modal.html");
      });
    </script>

    <!-- Header -->
    <header class="masthead">
      <div class="textlanding">
        <h1>Most basic hierarchical edge bundling in d3.js</h1>
        <hr class="short_hr" />
        <br />
        <ul class="list-inline social-buttons">
          <li class="list-inline-item">
            <a href="https://twitter.com/R_Graph_Gallery">
              <i class="fa fa-twitter"></i>
            </a>
          </li>
          <li class="list-inline-item social-buttons">
            <a href="https://github.com/holtzy">
              <i class="fa fa-github" style="color: white"></i>
            </a>
          </li>
          <li class="list-inline-item social-buttons">
            <a href="https://www.linkedin.com/in/yan-holtz-2477534a/">
              <i class="fa fa-linkedin"></i>
            </a>
          </li>
          <li class="list-inline-item social-buttons">
            <a href="https://www.yan-holtz.com">
              <i class="fa fa-home"></i>
            </a>
          </li>
        </ul>
        <br /><br />
        <p style="max-width: 700px; margin: auto">
          This post describes how to build a very basic
          <a href="../bundle.html">hierarchical edge bundling</a> with d3.js.
          You can see many other examples in the
          <a href="../bundle.html">hierarchical edge bundling section</a> of the
          gallery. Learn more about the theory of this chart in
          <a href="https://www.data-to-viz.com/graph/edge_bundling.html"
            >data-to-viz.com</a
          >.
        </p>
        <br />
        <a class="btn btn-secondary btn-md text-uppercase" href="../bundle.html"
          >Hierarchical edge bundling section</a
        >
        <button
          class="btn btn-secondary btn-md text-uppercase"
          onclick="myCodeDownload('chart_example_from_d3-graph-gallery.html', 'code', 'codejs')"
        >
          Download code
        </button>
      </div>
    </header>

    <section class="bg" style="padding-top: 20px; padding-bottom: 20px">
      <div class="container">
        <div class="row">
          <!-- ==================== GRAPH SECTION = WHERE THE GRAPH APPEARS ==================== -->

          <div class="col-lg-6 .align-middle">
            <div style="position: -webkit-sticky; position: sticky; top: 120px">
              <div class="bg-light" id="result"></div>
              <br />
              <div>
                <h5>Steps:</h5>
                <ul>
                  <br />
                  <li>
                    The
                    <a
                      href="https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/data_hierarchical_edge_bundling.json"
                      >dataset</a
                    >
                    is an array. Each item represents a node of the underlying
                    hierarchy. This node has a name, a numeric value used for
                    the bubble, and a list of connections.
                  </li>
                  <br />
                  <li>
                    The <code>cluster()</code> function is used to compute the
                    position of each node as a circular
                    <a href="../dendrogram.html">dendrogram</a>. Have a look to
                    the related
                    <a href="../dendrogram.html">dendrogram section</a> of the
                    gallery to understand that step.
                  </li>
                  <br />
                  <li>
                    Once the nodes are positioned, links are done thanks to the
                    <code>radialLine</code> and
                    <code>curveBundle</code> functions.
                  </li>
                </ul>
              </div>
            </div>
          </div>

          <!-- ================================================================================= -->

          <!-- ==================== CODE SECTION = WHERE THE CODE APPEARS ==================== -->
          <div class="col-lg-6 text-center .align-middle">
            <!-- ========= show html code ============== -->
            <aside
              style="position: -webkit-sticky; position: sticky; top: 120px"
            >
              &larr; Edit me!
            </aside>
            <pre
              class="language-html d-none d3v4-chunk"
            ><code id="code-html-v4" contenteditable="true"><xmp><!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>

</xmp></code></pre>
            <!-- ==================================== -->

            <!-- ========= show JS code ==============  -->
            <pre
              class="language-js d-none d3v4-chunk"
            ><code id="code-js-v4" contenteditable="true"><xmp><script>
// Some constants controlling the graph appearance
const PADDING_BUBBLE = 15 // distance between edge end and bubble
const PADDING_LABEL = 30 // distance between edge end and engineer name
const BUBBLE_SIZE_MIN = 4
const BUBBLE_SIZE_MAX = 20

var diameter = 560,
    radius = diameter / 2,
    innerRadius = radius - 170; // between center and edge end

// The 'cluster' function takes 1 argument as input. It also has methods (??) like cluster.separation(), cluster.size() and cluster.nodeSize()
var cluster = d3.cluster()
    .size([360, innerRadius]);

var line = d3.radialLine()
    .curve(d3.curveBundle.beta(0.85))
    .radius(function (d) { return d.y; })
    .angle(function (d) { return d.x / 180 * Math.PI; });

var svg = d3.select("#my_dataviz").append("svg")
    .attr("width", diameter)
    .attr("height", diameter)
    .append("g")
    .attr("transform", "translate(" + radius + "," + radius + ")");

var link = svg.append("g").selectAll(".link"),
    label = svg.append("g").selectAll(".label"),
    bubble = svg.append("g").selectAll(".bubble");

// Add a scale for bubble size
var bubbleSizeScale = d3.scaleLinear()
    .domain([0, 100])
    .range([BUBBLE_SIZE_MIN, BUBBLE_SIZE_MAX]);

// Scale for the bubble size
d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/data_hierarchical_edge_bundling.json", function (error, hierarchicalData) {

    // If wanna see your data
    // console.log(hierarchicalData)

    // Reformat the data
    var root = packageHierarchy(hierarchicalData)
        //debugger;
        .sum(function (d) { console.log(d); return d.size; });
    // console.log(root)

    // Build an object that gives feature of each leaves
    cluster(root);
    leaves = root.leaves()

    // Leaves is an array of Objects. 1 item = one leaf. Provides x and y for leaf position in the svg. Also gives details about its parent.
    link = link
        .data(packageImports(leaves))
        .enter().append("path")
        .each(function (d) { d.source = d[0], d.target = d[d.length - 1]; })
        .attr("class", "link")
        .attr("d", line)
        .attr("fill", "none")
        .attr("stroke", "black")

    label = label
        .data(leaves)
        .enter().append("text")
        .attr("class", "label")
        .attr("dy", "0.31em")
        .attr("transform", function (d) { return "rotate(" + (d.x - 90) + ")translate(" + (d.y + PADDING_LABEL) + ",0)" + (d.x < 180 ? "" : "rotate(180)"); })
        .attr("text-anchor", function (d) { return d.x < 180 ? "start" : "end"; })
        .text(function (d) { return d.data.key; });

    bubble = bubble
        .data(leaves)
        .enter().append("circle")
        .attr("class", "bubble")
        .attr("transform", function (d) { return "rotate(" + (d.x - 90) + ")translate(" + (d.y + PADDING_BUBBLE) + ",0)" })
        .attr('r', d => bubbleSizeScale(d.value))
        .attr('stroke', 'black')
        .attr('fill', '#69a3b2')
        .style('opacity', .2)

})

// Lazily construct the package hierarchy from class names.
function packageHierarchy(classes) {
    var map = {};

    function find(name, data) {
        var node = map[name], i;
        if (!node) {
            node = map[name] = data || { name: name, children: [] };
            if (name.length) {
                node.parent = find(name.substring(0, i = name.lastIndexOf(".")));
                node.parent.children.push(node);
                node.key = name.substring(i + 1);
            }
        }
        return node;
    }

    classes.forEach(function (d) {
        find(d.name, d);
    });

    return d3.hierarchy(map[""]);
}

// Return a list of imports for the given array of nodes.
function packageImports(nodes) {
    var map = {},
        imports = [];

    // Compute a map from name to node.
    nodes.forEach(function (d) {
        map[d.data.name] = d;
    });

    // For each import, construct a link from the source to target node.
    nodes.forEach(function (d) {
        if (d.data.imports) d.data.imports.forEach(function (i) {
            imports.push(map[d.data.name].path(map[i]));
        });
    });

    return imports;
}
                    </script></xmp></code></pre>
            <!-- ==================================== -->
          </div>
        </div>
      </div>
    </section>
    <br />

    <!-- ============================ -->

    <!-- ============================ RELATED BLOCKS ============================ -->

    <section class="bg-light" style="padding-top: 70px; padding-bottom: 70px">
      <div class="container">
        <div class="row">
          <div class="col-lg-5 text-center align-self-center">
            <h3 class="text-uppercase">Related blocks &rarr;</h3>
          </div>
          <div class="col-lg-5">
            <ul>
              <li>
                <i>Hierarchical Edge Bundling section - </i
                ><a href="../bundle.html">link</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </section>

    <!-- ============================ CONTACT SECTION ============================ -->

    <!-- ANCHOR -->
    <a name="contactanchor"></a>

    <section id="contact" class="bg" style="background-color: white"></section>

    <!-- THIS ALLOWS TO INSERT THE CONTACT CHUNK THAT IS STORED IN A CONTACT.HTML FILE-->
    <script>
      $(function () {
        $("#contact").load("../html_chunk/contact.html");
      });
    </script>

    <script>
      showCodeVersion("v4");
    </script>

    <!-- ============================ FOOTER SECTION ============================ -->
    <footer class="bg-light" id="myFooter"></footer>

    <!-- Start Added by AdThrive -->
    <script
      type="text/javascript"
      async
      src="https://btloader.com/tag?o=5698917485248512&upapi=true&domain=d3-graph-gallery.com"
    ></script>
    <script>
      !(function () {
        "use strict";
        var e;
        (e = document),
          (function () {
            var t, n;
            function r() {
              var t = e.createElement("script");
              (t.src =
                "https://cafemedia-com.videoplayerhub.com/galleryplayer.js"),
                e.head.appendChild(t);
            }
            function a() {
              var t = e.cookie.match("(^|[^;]+)\s*__adblocker\s*=\s*([^;]+)");
              return t && t.pop();
            }
            function c() {
              clearInterval(n);
            }
            return {
              init: function () {
                var e;
                "true" === (t = a())
                  ? r()
                  : ((e = 0),
                    (n = setInterval(function () {
                      (100 !== e && "false" !== t) || c(),
                        "true" === t && (r(), c()),
                        (t = a()),
                        e++;
                    }, 50)));
              },
            };
          })().init();
      })();
    </script>
    <!-- End Added by AdThrive -->

    <!-- THIS ALLOWS TO INSERT THE FOOTER THAT IS STORED IN A FOOTER.HTML FILE-->
    <script>
      $(function () {
        $("#myFooter").load("../html_chunk/footer.html");
      });
    </script>

    <!-- ============================ -->

    <!-- ============================ JAVASCRIPT SECTION ============================ -->

    <!-- Bootstrap core JavaScript -->
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Custom scripts for this template -->
    <script src="../js/agency.min.js"></script>

    <!-- Activate the bootstrap tooltip, must be after jQuery load -->
    <script>
      $(function () {
        $('[data-toggle="tooltip"]').tooltip();
      });
    </script>

    <script>
      function download() {
        var a = document.body.appendChild(document.createElement("a"));
        a.download = "export.html";
        var command = document.getElementById("code").innerHTML;
        command = command.replace(/<\/?span[^>]*>/g, "");
        a.href = "data:html" + command;
        a.click(); // Trigger a click on the element
      }
    </script>
  </body>
</html>
